var BluetoothTool = (function() {
  var respData = []
  var dataSendLen = 0 //帧发送的长度
  var allMsgArr = [] //所有需要发送的数据，按长度不超17字节截取在这里
  var getMsgFlag = true //每次发送是否已经收到了返回消息
  var startSendIndex = 0 //发送消息时从哪一帧开始发送
  var eachRespData = [] //每次接收的帧返回来的消息

  function BluetoothTool() {
    var BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter')
    this.mAdapter = BluetoothAdapter.getDefaultAdapter()
    this.BluetoothAdapter = BluetoothAdapter
    this.BTSocket = null
  }
  /**
   * 是否支持蓝牙
   * @return {boolean}
   */
  BluetoothTool.prototype.isSupportBluetooth = function() {
    var mAdapter = this.mAdapter
    if (mAdapter != null) {
      return true
    }
    return false
  }
  /**
   * 获取蓝牙的状态
   * @return {boolean} 是否已开启
   */
  BluetoothTool.prototype.getBluetoothStatus = function() {
    var mAdapter = this.mAdapter
    if (mAdapter != null) {
      return mAdapter.isEnabled()
    }
    return false
  }

  /**
   * 打开蓝牙
   * @param activity
   * @param requestCode
   */
  BluetoothTool.prototype.turnOnBluetooth = function(activity, requestCode) {
    var mAdapter = this.mAdapter
    if (mAdapter != null && !mAdapter.isEnabled()) {
      var Intent = plus.android.importClass('android.content.Intent')
      var intent = new Intent(this.BluetoothAdapter.ACTION_REQUEST_ENABLE)
      activity.startActivityForResult(intent, requestCode)
    }
  }

  /**
   * 关闭蓝牙
   */
  BluetoothTool.prototype.turnOffBluetooth = function() {
    if (this.mAdapter != null && this.mAdapter.isEnabled()) {
      this.mAdapter.disable()
      this.BTSocket = null
    }
  }

  /**
   * 获取已经配对的设备
   * @return {Array} connetedDevices
   */
  BluetoothTool.prototype.getConnetedDevices = function() {
    var mAdapter = this.mAdapter
    var connetedDevices = []

    //蓝牙连接android原生对象，是一个set集合
    var connetedDevicesAndroid = null
    if (mAdapter != null && mAdapter.isEnabled()) {
      connetedDevicesAndroid = mAdapter.getBondedDevices()
    }

    if (!connetedDevicesAndroid) {
      return connetedDevices
    }
    //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    //遍历连接设备的set集合，转换为js数组
    var invoke = plus.android.invoke
    var it = invoke(connetedDevicesAndroid, 'iterator')
    while (plus.android.invoke(it, 'hasNext')) {
      var device = plus.android.invoke(it, 'next')
      connetedDevices.push({
        name: plus.android.invoke(device, 'getName'),
        address: plus.android.invoke(device, 'getAddress')
      })
    }
    return connetedDevices
  }

  /**
   * 发现拉亚设备
   * @param {Object} activity 当前活动界面
   * @param {Object} newDevices 用于接收发现的设备
   */
  BluetoothTool.prototype.findDevices = function(activity, newDevices) {
    var mAdapter = this.mAdapter

    var IntentFilter = plus.android.importClass('android.content.IntentFilter')
    var BluetoothDevice = plus.android.importClass('android.bluetooth.BluetoothDevice')
    var filter = new IntentFilter()
    // var BroadcastReceiver = plus.android.importClass('android.content.BroadcastReceiver')

    var BTReceiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {
      onReceive: function(context, intent) {
        plus.android.importClass(context)
        plus.android.importClass(intent)

        var action = intent.getAction()
        //发现了设备
        if (BluetoothDevice.ACTION_FOUND == action) {
          //从Intent中获取设备的BluetoothDevice对象
          var device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
          newDevices.push({
            name: plus.android.invoke(device, 'getName'),
            address: plus.android.invoke(device, 'getAddress')
          })
        }
      }
    })

    filter.addAction(BluetoothDevice.ACTION_FOUND)
    filter.addAction(this.BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
    activity.registerReceiver(BTReceiver, filter)

    mAdapter.startDiscovery() //开启搜索

  }
  // 获取蓝牙服务列表
  // BluetoothTool.prototype.getServices = function(activity, newDevices) {
  //   plus.bluetooth.getBLEDeviceServices({
  //     deviceId: deviceId,
  //     success: function(e) {
  //       var services = e.services

  //       for (var i in services) {

  //       }
  //     },
  //     fail: function(e) {

  //     }
  //   })
  // }
  /**
   * 根据蓝牙地址，连接设备
   * @param {Object} address
   * @return {Boolean}
   */
  BluetoothTool.prototype.connDevice = function(activity, address) {
    var invoke = plus.android.invoke

    var mAdapter = this.mAdapter

    var device = null
    var BluetoothDevice = plus.android.importClass('android.bluetooth.BluetoothDevice')
    var UUID = plus.android.importClass('java.util.UUID')
    var Toast = plus.android.importClass('android.widget.Toast')

    var MY_UUID = UUID.fromString('00001101-0000-1000-8000-00805F9B34FB')
    var btSocket = null
    return new Promise((resolve, reject) => {
      try {
        device = invoke(mAdapter, 'getRemoteDevice', address)
        btSocket = invoke(device, 'createRfcommSocketToServiceRecord', MY_UUID)
        this.btSocket = btSocket
        //初始化设备
        plus.bluetooth.openBluetoothAdapter({
          success: function(e) {
            /**
             * 当前设备状态 device.getBondState() 10
             * 11 正在配对 BluetoothDevice.BOND_BONDING
             * 12 完成配对 BluetoothDevice.BOND_BONDED
             * 10 取消配对 BluetoothDevice.BOND_NONE
             */

            if (device.getBondState() === BluetoothDevice.BOND_BONDED) {
              //完成配对
              plus.bluetooth.createBLEConnection({
                deviceId: address,
                success: function(e) {
                  // alert(JSON.stringify(e) + 'success')
                  console.log(address)
                  // alert(address + '蓝牙地址')
                  resolve(e)
                  readData(address)
                },
                fail: function(e) {
                  // alert(JSON.stringify(e) + 'fail')
                  reject(e)
                },
                complete: function(e) {}
              })
            } else {
              // 配对
              // alert(JSON.stringify(e) + 'else')
              invoke(device, 'createBond')
            }
          },
          fail: function(e) {
            // alert(JSON.stringify(e) + 'failTwo')
            reject(e)
            Toast.makeText('初始化失败')
          }
        })
      } catch (e) {
        // alert(JSON.stringify(e) + 'catch')
        Toast.makeText(activity, '连接失败，获取Socket失败！', Toast.LENGTH_SHORT).show()
        reject(e)
      }
    })
  }

  /**
   * 读取数据
   * @param {Object} activity
   * @param {Function} callback
   * @return {Boolean}
   */
  function readData(deviceId) {
    // alert('读取数据')
    setTimeout(function() {
      plus.bluetooth.notifyBLECharacteristicValueChange({
        deviceId: deviceId,
        serviceId: '6E400001-B5A3-F393-E0A9-E50E24DCCA9E',
        characteristicId: '6E400003-B5A3-F393-E0A9-E50E24DCCA9E',
        success: function(e) {
          // alert('readData ===== success: ' + JSON.stringify(e))
        },
        fail: function(e) {
          // alert('readData ===== failed: ' + JSON.stringify(e))
        },
        complete: function(e) {
          // alert(JSON.stringify(e) + 'complete')
        }
      })
    }, 2000)
    clearInterval(setIntervalId)
    var setIntervalId = setInterval(function() {
      // 监听低功耗蓝牙设备的特征值变化
      plus.bluetooth.onBLECharacteristicValueChange(function(e) {
        // alert(JSON.stringify(e) + '定时e jinlai le ')
        if (e.value != undefined) {
          // alert(buffer2hex(e.value))
          let endFlag = confirm4b(e.value, deviceId)
          // alert(endFlag + JSON.stringify(endFlag) + '=========endFlag')
          if (endFlag == '4b') {
            startSendIndex++
            continueSend(deviceId)
          } else if (endFlag == 'end') {
            // alert(buffer2hex(e.value) + 'e.value1')
            respData.push(eachRespData.join(''))
            eachRespData = []
            e.value = respData.join('')
            // alert(e.value + '-------------e.valyue' + typeof e.value)
            if (e.value != '') {
              localStorage.setItem('fhbw', e.value)
            }
          } else if (endFlag == 'oneEnd') {
            // alert(buffer2hex(e.value) + 'e.value2')
            return
          }
        }
      })
    }, 40)
  }
  function confirm4b(value, deviceId) {
    let dataView = new DataView(value)
    let firstBF = dataView.getUint8(0)
    firstBF = parseInt(firstBF, 10).toString(16)
    firstBF = firstBF.toLocaleLowerCase()
    let secondBF = dataView.getUint8(1)
    //如果接收到的是4b确认帧
    if (firstBF.indexOf('4b') > -1) {
      getMsgFlag = true
      return '4b'
    } else {
      for (var i = 0; i < value.byteLength; i++) {
        if (i >= 3) {
          var bf = dataView.getUint8(i)
          let rbf = bf.toString(16)
          if (rbf.length == 1) {
            rbf = '0' + rbf
          }
          eachRespData.push(rbf)
        }
      }
      //ctrl如果是以11 或 01 表示结束
      let binSecondBF = parseInt(secondBF, 10).toString(2)
      let binSecondBFLen = binSecondBF.length
      //如果少于8位，在前面补0
      if (binSecondBFLen < 8) {
        binSecondBF = '00000000'.substr(0, 8 - binSecondBFLen) + binSecondBF
      }
      let bit6 = binSecondBF.substr(1, 1)
      getMsgFlag = true
      //如果第6位是1表示传输结束
      if (bit6 == 1) {
        //发送确认消息
        confirmSend(secondBF, deviceId)
        return 'end'
      }
      //发送确认消息
      confirmSend(secondBF, deviceId)
      return 'oneEnd'
    }
  }

  function confirmSend(secondBF, deviceId) {
    let cbf = new ArrayBuffer(3)
    let dataView = new DataView(cbf)
    dataView.setUint8(0, 0x4b)
    let ctrl = secondBF | 0b00100000
    let ctrl16 = parseInt(ctrl, 10).toString(16)
    if (ctrl16.length == 1) {
      ctrl16 = '0' + ctrl16
    }
    dataView.setUint8(1, '0x' + ctrl16)
    dataView.setUint8(2, 0x00)
    var serviceId = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'
    var characteristicId = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E'
    plus.bluetooth.writeBLECharacteristicValue({
      deviceId: deviceId,
      serviceId: serviceId,
      characteristicId: characteristicId,
      value: cbf,
      success: function(res) {
        console.log('发送确认指令成功')
        console.log(res)
      },
      fail: function(res) {
        console.warn('发送确认指令失败', res)
      }
    })
  }

  // 接到sendData的数据发送
  function continueSend(deviceId) {
    // alert('接到sendData的数据发送')
    if (startSendIndex > dataSendLen - 1) {
      return
    }
    if (getMsgFlag) {
      getMsgFlag = false
      // 发送之前转换buffer
      let tranMsg = str2ab(allMsgArr[startSendIndex], startSendIndex, allMsgArr)
      console.log(buffer2hex(tranMsg) + 'tranMsg')
      // 蓝牙服务ID
      var serviceId = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'
      var characteristicId = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E'
      return new Promise((resolve, reject) => {
        plus.bluetooth.writeBLECharacteristicValue({
          deviceId: deviceId,
          serviceId: serviceId,
          characteristicId: characteristicId,
          value: tranMsg,
          success: function(e) {
            // alert('接到sendData的数据发送--success: ' + JSON.stringify(e))
            resolve(e)
          },
          fail: function(e) {
            // alert('接到sendData的数据发送--failed: ' + JSON.stringify(e))
            reject(e)
          },
          complete: function(e) {
            console.log(e)
          }
        })
      })
    }
  }

  function str2ab(str, index, msgArr) {
    let strByteLen = str.length / 2
    var buf = new ArrayBuffer(strByteLen + 3)
    let dataView = new DataView(buf)
    dataView.setUint8(0, 0x4a) //0x4a
    dataView.setUint8(1, bit2ForHexadecimal(index, msgArr))
    //这里把长度转换成16进制数
    let hexLen = parseInt(strByteLen, 10).toString(16)
    if (hexLen.length == 1) {
      hexLen = '0' + hexLen
    }
    dataView.setUint8(2, '0x' + hexLen)
    for (var i = 0, strLen = str.length; i < strLen; i = i + 2) {
      var n = str.substr(i, 2)
      if (n.length == 1) {
        n = '0' + n
      }
      dataView.setUint8(i / 2 + 3, '0x' + n)
    }
    return buf
  }

  //生成控制字,index为第几帧数据，返回一个二时制的数据
  function bit2ForHexadecimal(index, msgArr) {
    let baseBit = 0b00000000
    let ctrlBit = 0
    let i = index + 1
    if (i == 1) {
      //如果第一帧，高位7为1，其它位为0；
      ctrlBit = 0b10000000
    }
    if (msgArr.length == i) {
      //如果是最后一帧，高位为0，bit6为1，最低帧为顺序加1
      ctrlBit = ctrlBit ^ (0b01000000 ^ (i - 1))
    } else {
      if (ctrlBit) {
        //如果第一帧的话，最低位要顺序加1
        ctrlBit = ctrlBit ^ (baseBit ^ (i - 1))
      } else {
        ctrlBit = baseBit ^ (i - 1)
      }
    }
    //ctrlBit会自动变成10进制
    //这里把10进制的ctrlBit转成16进制
    let ctrlBit16 = parseInt(ctrlBit, 10).toString(16)
    if (ctrlBit16.length < 2) {
      ctrlBit16 = '0x0' + ctrlBit16
    } else {
      ctrlBit16 = '0x' + ctrlBit16
    }
    return ctrlBit16
  }

  /**
   * 发送数据
   * @param {Object} activity
   * @param {Function} callback
   * @return {Boolean}
   */
  BluetoothTool.prototype.sendData = function(deviceId, sendData) {
    //这里隔17个字节截取一次到数组中 // var sendData = "4AC010681800002001136811043235c3338e16"
    // alert('发送数据')
    let msgArr = []
    dataSendLen = 0
    respData = []

    for (let i = 0; i < sendData.length; i = i + 34) {
      msgArr.push(sendData.substr(i, 34))
    }
    dataSendLen = msgArr.length
    allMsgArr = msgArr
    startSendIndex = 0
    continueSend(deviceId)
  }

  /**
   * 读取的数据 格式转换
   * @param byte数组
   * @returns {string}
   */
  function buffer2hex(buffer) {
    var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function(bit) {
      return ('00' + bit.toString(16)).slice(-2)
    })
    return hexArr.join('')
  }

  return BluetoothTool
})()

export default BluetoothTool
